<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>Tracker</title>
  <link rel="stylesheet" href="/static/layui-v2.5.5/css/layui.css">
  <link rel="stylesheet" href="/static/layui-formSelects-master/dist/formSelects-v4.css">
  <link rel="stylesheet" href="/static/Font-Awesome-master/css/all.css" >
  <link rel="stylesheet" href="https://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
  <link rel="icon" href="/static/img/default.ico">
<!-- 滚动条样式设置开始 -->
<style type="text/css">
.layui-card::-webkit-scrollbar {
  width: 8px;
  background-color: #eee;
}

.layui-card::-webkit-scrollbar-track {
    background-color: #eee;
}

.layui-card::-webkit-scrollbar-thumb {
    background: #3DB6A4;
}

.layui-card::-webkit-scrollbar-button:start {
    background: url(/static/img/up.png) no-repeat;
    background-size: 8px 8px;
}

.layui-card::-webkit-scrollbar-button:end {
    background: url(/static/img/down.png) no-repeat;
    background-size: 8px 8px;
} 
::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
::-webkit-scrollbar-button,
::-webkit-scrollbar-button:vertical {
  display: none;
}
::-webkit-scrollbar-track,
::-webkit-scrollbar-track:vertical {
  background-color: #eee;
}
::-webkit-scrollbar-track-piece {
  background-color: #eee;
}
::-webkit-scrollbar-thumb,
::-webkit-scrollbar-thumb:vertical {
  margin-right: 10px;
  background-color: #3DB6A4;
}
::-webkit-scrollbar-thumb:hover,
::-webkit-scrollbar-thumb:vertical:hover {
  background-color: #eee;
}
::-webkit-scrollbar-corner,
::-webkit-scrollbar-corner:vertical {
  background-color: #eee;
}
::-webkit-scrollbar-resizer,
::-webkit-scrollbar-resizer:vertical {
  background-color: #eee;
}

</style>
<!-- 滚动条样式设置结束 -->
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
  <div class="layui-header">
    <div class="layui-logo"></div>
    <!-- 头部区域（可配合layui已有的水平导航） -->
    <!-- 顶部部导航栏左侧start -->
    <ul class="layui-nav layui-layout-left">
      <li class="layui-nav-item" id="dynamic" onclick="turn_to_page(this.id)"><a href="#dynamic"><i class="layui-icon layui-icon-location"></i> 实时监控</a></li>
      <li class="layui-nav-item" id="trail" onclick="turn_to_page(this.id)"><a href="#trail"><i class="layui-icon layui-icon-engine"></i> 活动轨迹</a></li>
      <li class="layui-nav-item" id="reports" ><a><i class="layui-icon layui-icon-chart"></i> 统计报表</a>
        <dl class="layui-nav-child">
          <dd class="" id="device_report"  onclick="turn_to_page(this.id)"><a href="#device_report">设备运行统计</a></dd>
          <dd class="" id="health_report" onclick="turn_to_page(this.id)"><a href="#health_report">健康数据统计</a></dd>
          <dd class="" id="health_alarm_report"  onclick="turn_to_page(this.id)"><a href="#health_alarm_report">报警统计</a></dd>
        </dl>
      </li>
      <li class="layui-nav-item" id="base_info_manage" ><a><i class="layui-icon layui-icon-app"></i> 基础信息</a>
        <dl class="layui-nav-child">
          <dd class="" id="device_manage"  onclick="turn_to_page(this.id)"><a href="#device_manage">设备管理</a></dd>
          <dd class="alarm_report" id="building"  onclick="turn_to_page(this.id)"><a href="#building">建筑管理</a></dd>
          <dd class="alarm_report" id="scanner"  onclick="turn_to_page(this.id)"><a href="#scanner">基站管理</a></dd>
          <dd class="alarm_report" id="map_manage"  onclick="turn_to_page(this.id)"><a href="#map_manage">地图管理</a></dd>
        </dl>
      </li>
      <li class="layui-nav-item" id="efence" onclick="turn_to_page(this.id)"><a href="#efence"><i class="layui-icon layui-icon-auz"></i> 电子围栏</a></li>
      <li class="layui-nav-item" id="tracker_sys_manage" ><a><i class="layui-icon layui-icon-set"></i> 系统管理</a>
        <dl class="layui-nav-child">
          <dd class="" id="user_manage" onclick="turn_to_page(this.id)"><a href="#user_manage">子用户管理</a></dd>
          <dd class="" id="system_log" onclick="turn_to_page(this.id)"><a href="#system_log">系统日志</a></dd>
        </dl>
      </li>
    </ul>
    <!-- 顶部部导航栏左侧end -->

    <!-- 顶部部导航栏右侧start -->
    <ul class="layui-nav layui-layout-right">
      <li class="layui-nav-item"><a id="get_current_time"></a></li>
      <li class="layui-nav-item" id="alarm_detail_show" onclick="alarm_detail_modal()"><a href="#"><i class="layui-icon layui-icon-notice"></i><span id="alarm_num_show" class="layui-badge"></span></a></li>
      <li class="layui-nav-item">
        <a href="javascript:;" id="username_show">
          <!-- <img src="/static/img/default.png" class="layui-nav-img"> -->
        </a>
         <dl class="layui-nav-child">
          <dd class="user_self_btn"><a href="javascript:;">基本资料</a></dd>
          <dd class="user_password_btn"><a href="javascript:;">安全设置</a></dd>
        </dl>
      </li>
      <li class="layui-nav-item"><a href="/">退出</a></li>
    </ul>
  </div>

  <!-- 顶部部导航栏右侧end -->

  <!-- 侧边栏内容start -->
  <div class="layui-side" id="side1">
    <div class="layui-coutainer" id="dynamic_side_bar">
      <div  style="overflow: auto;height: 165px;">
        <table id="id_tree" class="layui-table"></table>
      </div>
     <!--  <div style="height: 20px;padding: 1px">全部</div> -->
      <div class="layui-row" style="padding: 0px;background-color:#009688;text-align: center;">
        <button id="user_chosed" class="layui-btn layui-btn-xs layui-btn-fluid" onclick="device_status_search('all')">全部</button>
      </div>
      <div class="layui-row" style="padding: 2px;">
    		<button id="dev_online" class="layui-btn layui-btn-xs layui-btn-radius" onclick="device_status_search('online')">在线</button>
    		<button id="dev_sleep" class="layui-btn layui-btn-normal layui-btn-xs layui-btn-radius" onclick="device_status_search('sleep')">休眠</button>
    		<button id="dev_offline" class="layui-btn layui-bg-cyan layui-btn-xs layui-btn-radius" onclick="device_status_search('offline')">离线</button>
    		<button id="dev_alarm" class="layui-btn layui-btn-danger layui-btn-xs layui-btn-radius" onclick="device_status_search('alarm')">报警</button>
      </div>
     <form class="layui-form layui-form-pane" action="" style="width:auto;height: 20px;padding: 2px">
          <div class="layui-form-item">
              <div class="layui-inline">
                  <div class="layui-input-inline">
                      <input type="text" lay-verify="required" name="search_key" lay-reqtext="请输入搜索内容" placeholder="设备ID/名称" autocomplete="off" class="layui-input" style="width:auto;height: 30px">
                  </div>
                  <div class="layui-inline" >
                      <a type="button" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="dev-search-btn" >搜索</a>
                  </div>
              </div>
          </div>
      </form>
      <div class="" id="dev_list_panle">
        <div class="layui-card-body" style="padding: 2px;border: 1px">
          <table id="dev_list_show" lay-filter="dev_list_show"></table>
        </div>
      </div>
    </div>
  </div>
  <div class="" id="side2" style="display: none;"></div>
  <!-- 侧边栏内容end -->
  
  <!-- 内容主体区域sart -->

  <div class="layui-body" style="bottom: 0px">

  </div>

  <!-- 内容主体区域end -->
  <div class="layui-footer"></div>

</div>

<!-- 实时报警信息弹窗开始 -->

<!-- 单个报警处理按钮 -->
<script type="text/html" id="alarm_table_bar">
    <a class="layui-btn layui-btn-xs" lay-event="excue_alarm">处理</a>
</script>
<form  class="layui-form layui-form-pane " action="" id="alarm_detail_form" lay-filter="alarm_detail_form" style="padding: 10px;display: none;">
  <table class="layui-table" id="alarm_detail_table" lay-size="lg" lay-filter="alarm_detail_table">
  </table>
</form>
<!-- 报警信息批量处理按钮 -->
<script type="text/html" id="alarm_handle_bar">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" type="button" lay-event="alarm_handle">批量处理</button>
    <button class="layui-btn layui-btn-sm" type="button" lay-event="all_alarm_handle">全部处理</button>
  </div>
</script>
<!-- 报警处理备注框 -->
<form  class="layui-form layui-form-pane " action="" id="alarm_handle_mark_form" lay-filter="alarm_handle_mark_form" style="padding: 10px;display: none;">
	<textarea placeholder="请输入报警处理备注" class="layui-textarea" name="alarm_handle_mark"></textarea>
</form>
<!-- 报警声音 -->
<audio loop="loop" id="alarm_audio_play" src="/static/audio/didi.mp3"></audio>

<!-- 实时报警信息弹窗结束 -->


<!-- 引用layui模块 -->

<script type="text/javascript" src="/static/layui-v2.5.5/layui.all.js"></script>
<script type="text/javascript" src="/static/layui-formSelects-master/dist/formSelects-v4.js"></script>
<!-- 百度api的https引用 -->
<script type="text/javascript">window.HOST_TYPE='2'</script>
<script type="text/javascript" src="https://api.map.baidu.com/getscript?v=2.0&ak=nSxiPohfziUaCuONe4ViUP2N&s=1"></script> 
<!-- <script type="text/javascript" src="http://api.map.baidu.com/library/LuShu/1.2/src/LuShu_min.js"></script> -->
<script type="text/javascript" src="/static/efence_tool.js"></script>
<!-- <script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script> -->



<!-- JavaScript代码区域 -->
<script type="text/javascript">

var $=layui.jquery;

var device={{device|safe}};
console.log(device)
var dev_model={{dev_model|safe}};

var dev_model_objs={}
for(var i=0;i<dev_model.length;i++){
  dev_model_objs[dev_model[i].unique_id]=dev_model[i]
}
console.log(dev_model_objs)
var user_tree={{user_tree|safe}};
user_tree.unshift({'name':'all','title':'全部'})
var user_data={{user_data|safe}};
var user_self={{user_self|safe}};
var user_info_objs={}
for(var i=0;i<user_data.length;i++){
  user_info_objs[user_data[i].username]=user_data[i]
}
user_info_objs[user_self[0].username]=user_self[0]
var alarm_data={{alarm_data|safe}};
console.log(alarm_data)
// 记录当前选中的设备的全局变量
var chosed_dev={'device_id':'default'};

// --用户设置赋值处理开始-------------------

var user_self_detail={}
var contact_info=eval('('+user_self[0]['level']+')')
user_self_detail['visible_name']=user_self[0]['visible_name']
user_self_detail['email']=user_self[0]['email']
user_self_detail['remark']=user_self[0]['remark']
user_self_detail['contact']=contact_info[0]
user_self_detail['phone']=contact_info[1]
// 用户参数数据提取
var character=eval('('+user_self[0]['character']+')')
// 显示图标
var user_icon=character['user_icon'];
// 报警声音,弹窗，刷新时间
user_self_detail['alarm_audio']=true
if(character['alarm_audio']==='off'){
  user_self_detail['alarm_audio']=false
}

user_self_detail['alarm_show']=true;
if(character['alarm_show']==='off'){
  user_self_detail['alarm_show']=false
}
user_self_detail['refresh_time']=character['refresh_time']
user_self_detail['sys_name']=character['sys_name']
if(user_self_detail['sys_name']==null){
  user_self_detail['sys_name']='Aiot'
}

// 刷新时间,从用户设置当中选择，最小10秒刷新一次，低于10秒或者不是数字，默认60秒刷新
var param_refresh_time_control=parseInt(user_self_detail['refresh_time'])*1000
if(typeof(param_refresh_time_control)!=='Number' | param_refresh_time_control<10000){
  param_refresh_time_control=60000;
}

// 用户权限，只能查看，能编辑，能分配，能导入，四个级别
user_permi=character['kind']
if(user_permi=='普通用户' | user_permi=='phone_user'){
  $('#user_manage').hide()
}
handle_dev_permi=character['handle_device']

// 右上角的用户显示名称和图标,
var username_show='<img src="'+user_icon+'" class="layui-nav-img">'+user_self_detail['visible_name']
$('#username_show').append(username_show)
// 左上角的显示的系统名称
// $('.layui-logo').text(user_self_detail['sys_name'].slice(0,8))
var sys_name_add='<a><img id="kanban" src="/static/img/logo.png" style="position:absolute;top:-10px;left:0px;width:'+get_width/20+'px"></a>'
$('.layui-logo').append(sys_name_add)
if(user_permi=='superuser'){
  $('.layui-logo').click(function(){
    turn_to_page('kanban')
  })
}





// --用户设置赋值处理结束-------------------

var element = layui.element;
var tree=layui.tree;
var table=layui.table;
var layer=layui.layer;
var form=layui.form;
var upload=layui.upload;
var laydate=layui.laydate;
var slider=layui.slider;
var transfer=layui.transfer;
var formSelects = layui.formSelects;

// 获取屏幕高度和宽度

var get_height=$(window).height()
var get_width=$(window).width()

// 渲染树状用户结构，需要增加宽度，增加横向的滚动
tree.render({
    elem: '#id_tree'
    ,data: user_tree
    ,showCheckbox: false  //是否显示复选框
    ,onlyIconControl:true
    ,id: 'user_tree_id'
    ,isJump: true //是否允许点击节点时弹出新窗口跳转
    ,text: {
            defaultNodeName: '未命名' //节点默认名称
            ,none: '无数据' //数据为空时的提示文本
          }   
    // ,showLine:false
    ,click: function(obj){
      // 选择用户，展示该用户名下的设备
      var check_user = obj.data.name;
      var user_title= obj.data.title
      // 用户状态搜索展示
      user_check['name']=check_user
      user_check['title']=user_title
      var check_user_device=[];
      for(var i=0;i<device.length;i++){
         if(device[i]['owner']===check_user){
          check_user_device.push(device[i])
         }
      }
      if(check_user=='all'){
        device_list_table(device)
      }else{
        device_list_table(check_user_device)
      }
      dev_status_num(check_user,user_title)
    }
  });


// 设备列表框的高度处理
var dev_list_panle_height=get_height-330
// $('#dev_list_panle').attr('style','height:'+dev_list_panle_height+'px;overflow:auto')
// 设备列表数据加载函数
var device_list_table=function(table_data){
table.render({
    elem: '#dev_list_show',
    data: table_data,
    id:'device_list',
    skin:'nob',
    size:'sm',
    height: 'full-330',
    cols: [[
        {type: "checkbox", fixed: "left"},
        {field: 'user_name', title: '名称'},
        {field: 'device_id', title: '设备ID',sort:true},
        {field: 'on_off_line', title: '状态',sort:true,templet: function(d){
          var status;
          if(d.on_off_line==='online'){
            status='在'
          }else{
            status='离'
          }
        return status
      }}
    ]],
    // page: true,
    limit:10000000
  });
}
device_list_table(device)

// 按照设备状态展示设备
// 全局变量user_check,用户存储用户树状图上被选中的用户name和title
var user_check={'name':'all','title':'全部'};
var device_status_search=function(dev_status){
  // console.log(dev_status,user_check)
  var user_name=user_check['name']
  var query_status={'online':'on_off_line','sleep':'sleep_status','offline':'on_off_line','alarm':'alarm_status'}
  var dev_status_list=[]
  for(var i=0;i<device.length;i++){
    if(user_name=='all'){
      if(dev_status=='all'){
        dev_status_list.push(device[i])
      }else{
        if(device[i][query_status[dev_status]]==dev_status){
          dev_status_list.push(device[i])
        }
      }
    }else{
      if(dev_status=='all'){
        if(device[i]['owner']==user_name){
          dev_status_list.push(device[i])
        }
      }else{
        if(device[i]['owner']==user_name && device[i][query_status[dev_status]]==dev_status){
          dev_status_list.push(device[i])
        }
      }
    }
  }
  device_list_table(dev_status_list)
}

// 用户基本信息弹出
var user_set_modal='<div class="layui-coutainer layui-scroll"><form class="layui-form layui-form-pane " action="" id="user_self_form" lay-filter="user_self_form" style="padding: 10px;">'+

  '<div class="layui-form-item">'+

    '<div class="layui-inline">'+
      '<label class="layui-form-label layui-bg-green">显示名</label>'+
      '<div class="layui-input-block">'+
        '<input type="text" name="visible_name" lay-verify="required" autocomplete="off" placeholder="用户显示名称" class="layui-input">'+
      '</div>'+
    '</div>'+
    '<div class="layui-inline" >'+
      '<label class="layui-form-label layui-bg-green">系统logo</label>'+
      '<div class="layui-input-block">'+
        '<input type="text" name="sys_name" lay-verify="required" autocomplete="off" placeholder="" class="layui-input">'+
      '</div>'+
    '</div>'+
  '</div>'+

  '<div class="layui-form-item">'+
    '<div class="layui-inline">'+
      '<label class="layui-form-label layui-bg-green">邮箱</label>'+
      '<div class="layui-input-block">'+
        '<input type="text" name="email" lay-verify="email" placeholder="必填项"  autocomplete="off" class="layui-input">'+
      '</div>'+
    '</div>'+
  '<div class="layui-inline">'+
      '<label class="layui-form-label layui-bg-green">联系人</label>'+
      '<div class="layui-input-block">'+
        '<input type="text" name="contact" autocomplete="off" class="layui-input">'+
      '</div>'+
    '</div>'+
  '</div>'+

  '<div class="layui-form-item">'+
    '<div class="layui-inline">'+
      '<label class="layui-form-label layui-bg-green">电话</label>'+
      '<div class="layui-input-block">'+
        '<input type="text" name="phone" autocomplete="off" class="layui-input">'+
      '</div>'+
    '</div>'+
    '<div class="layui-inline">'+
      '<label class="layui-form-label layui-bg-green">备注</label>'+
      '<div class="layui-input-block">'+
        '<input type="text" name="remark" autocomplete="off" class="layui-input">'+
      '</div>'+
    '</div>'+
  '</div>'+

  '<div class="layui-form-item">'+
    '<div class="layui-block" >'+
      '<label class="layui-form-label layui-bg-green">刷新时间</label>'+
      '<div class="layui-input-inline">'+
        '<input type="text" name="refresh_time" autocomplete="off" placeholder="秒" class="layui-input">'+
      '</div>'+
    '</div>'+
     '<div class="layui-block" >'+
      '<label class="layui-form-label layui-bg-green">用户图标</label>'+
      '<div class="layui-input-inline">'+
        '<img type="text" name="user_icon" src="'+user_icon+'" style="width:80px;height:80px" id="user_icon">'+
      '</div>'+
    '</div>'+
  '</div>'+

  '<div class="layui-form-item">'+
  '<div class="layui-block" >'+
    '<label class="layui-form-label layui-bg-green">账户类型</label>'+
    '<div class="layui-input-inline">'+
      '<input type="text" autocomplete="off" class="layui-input" value="'+user_permi+'">'+
    '</div>'+
    '</div>'+
  '</div>'+

  '<div class="layui-form-item">'+
    '<label class="layui-form-label layui-bg-green">报警声音</label>'+
    '<div class="layui-input-block">'+
      '<input type="checkbox" checked="" name="alarm_audio" lay-skin="switch" lay-filter="switchTest" lay-text="ON|OFF">'+
    '</div>'+
  '</div>'+

  '<div class="layui-form-item">'+
    '<label class="layui-form-label layui-bg-green">报警弹窗</label>'+
    '<div class="layui-input-block">'+
      '<input type="checkbox" checked="" name="alarm_show" lay-skin="switch" lay-filter="switchTest" lay-text="ON|OFF">'+
    '</div>'+
  '</div>'+

  '<div class="layui-form-item">'+
    '<button class="layui-btn" lay-submit="" lay-filter="user_self_btn" id="user_self_btn" style="display: none;"></button>'+
  '</div>'+

'</form></div>'

// 监听 基本资料 按钮，做展示和修改操作处理
  $(".user_self_btn").on("click", function () {
        // document.getElementById("user_self_form").reset();
        // form.render();
        layer.open({
            type: 1
            ,title:['登录账户：'+user_self[0]['username'],'font-size:18px;']
            ,area:['700px','550px']
            ,offset:'60px'  
            ,id: 'user_self_data' //防止重复弹出
            ,content:user_set_modal
            ,success: function(layero, index){
                                                // 图片上传
                                                img_upload_func('user_icon')
                                                // console.log(user_self_detail)
                                                form.val('user_self_form',user_self_detail)
                                              }
            ,btn: ['提交','关闭']
            ,shade: 0 //不显示遮罩
            ,btn1: function(){
                if(user_self[0]['username']=='demo'){
                  layer.msg('无此权限！')
                  return false
                }
                $('#user_self_btn').click();
            }
            ,btn2: function(){
              layer.closeAll();
            }
          });
    });

    // 监听用户设置表单提交，修改名称，图标等数据
    form.on('submit(user_self_btn)', function (data) {  
        // 获取表单数据
        var result=data.field
        // 开关off的时候，表单没有该数据的键，需要进行判断
        if(result['alarm_show']==null){
          result['alarm_show']='off'
        }
        if(result['alarm_audio']==null){
          result['alarm_audio']='off'
        }
        result['file']=$('#user_icon')[0].src
        // console.log(result)
        result = JSON.stringify(result);

        $.ajax({
            type: 'POST',
            data:{result},
            url:"?what=handle_user_self",
            async:true,
            dataType: 'json',
            success: function(data) {
              // console.log(data)
              layer.msg('更新成功')
              location.reload();
            },
        });
        return false;
    });



// 安全设置弹出
var user_password_show='<div class="layui-coutainer layui-scroll"><form class="layui-form layui-form-pane " action="" id="user_password_form" lay-filter="user_password_form" style="padding: 10px;">'+

  '<fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">'+
    '<legend>修改密码</legend>'+
  '</fieldset>'+

  '<div class="layui-form-item">'+
    '<div class="layui-inline">'+
      '<label class="layui-form-label layui-bg-green">输入旧密码</label>'+
      '<div class="layui-input-block">'+
        '<input type="password" name="old_password" lay-verify="required" autocomplete="off"  class="layui-input">'+
      '</div>'+
    '</div>'+
  '</div>'+

  '<div class="layui-form-item">'+
    '<div class="layui-inline">'+
      '<label class="layui-form-label layui-bg-green">输入新密码</label>'+
      '<div class="layui-input-block">'+
        '<input type="password" name="new_password1" lay-verify="required" autocomplete="off"  class="layui-input">'+
      '</div>'+
    '</div>'+
  '</div>'+

  '<div class="layui-form-item">'+
    '<div class="layui-inline">'+
      '<label class="layui-form-label layui-bg-green">再次输入新密码</label>'+
      '<div class="layui-input-block">'+
        '<input type="password" name="new_password2" lay-verify="required" autocomplete="off"  class="layui-input">'+
      '</div>'+
    '</div>'+
  '</div>'+


  '<div class="layui-form-item">'+
    '<button class="layui-btn" lay-submit="" lay-filter="password_change_btn" id="password_change_btn" style="display: none;"></button>'+
  '</div>'+

'</form></div>'
// 监听 安全设置 按钮，做展示和修改操作处理
  $(".user_password_btn").on("click", function () {
        // document.getElementById("user_self_form").reset();
        // form.render();
        layer.open({
            type: 1
            ,title:['安全设置','font-size:18px;']
            ,area:['400px','500px']
            ,offset:'60px'  
            ,id: 'user_password_data' //防止重复弹出
            ,content:user_password_show
            ,success: function(layero, index){
                                              }
            ,btn: ['提交','关闭']
            ,shade: 0 //不显示遮罩
            ,btn1: function(){
                if(user_self[0]['username']=='demo'){
                  layer.msg('无此权限！')
                  return false
                }
                $('#password_change_btn').click();
            }
            ,btn2: function(){
              layer.closeAll();
            }
          });
    });

// 监听安全设置提交表单
form.on('submit(password_change_btn)', function (data) {  
    // 获取表单数据
    var result=data.field
    // console.log(result)
    result = JSON.stringify(result);

    $.ajax({
        type: 'POST',
        data:{result},
        url:"?what=handle_user_password",
        async:true,
        dataType: 'json',
        success: function(data) {
          // console.log(data)
          layer.msg(data[0])
          setTimeout(function(){
            window.location.href = '/';
          },1000)
          
        },
    });
    return false;
});



// 实时报警展示/处理开始

var alarm_detail_modal=function(){
	form.render()
    layer.open({
    type: 1
    ,title:'实时报警信息'
    ,area:['1080px',get_height-80+'px']
    ,offset:'60px'  
    ,id: 'alarm_data' //防止重复弹出
    ,content:$('#alarm_detail_form')
    // ,btn: '关闭'
    ,shade: 0 //不显示遮罩
    ,success:function(layero, index){
    	 table.render({
		    elem: '#alarm_detail_table',
		    data: alarm_data,
		    toolbar: '#alarm_handle_bar' ,
		    id:'alarm_detail_table',
		    skin:'nob',
		    size:'lg',
        height: get_height-200,
		    cols: [[
		    	{type: "checkbox", fixed: "left"},
          {field: 'index_num', title: '序号',width:10,templet:function(d){
            return d.LAY_INDEX
          }},
		    	{field: 'name', title: '设备名称',width:140,templet:function(d){
            console.log(d.device_id)
            var dev_name=get_detail_from_id(device,d.device_id)
            if(dev_name.user_detail!='0'){
              dev_name=dev_name.user_detail.name
            }else{
              dev_name=dev_name.user_name
            }
            return dev_name
          }},
	        {field: 'device_id', title: '设备ID'},
	        {field: 'kind', title: '报警类型',width:120,templet:function(d){
            alarm_kind_dict={'sos_alarm':'SOS报警','l_pres_low':'舒张压低报警','l_pres_hight':'舒张压高报警','h_pres_low':'收缩压低报警','h_pres_hight':'收缩压低报警',
                             'heart_low':'心率低报警','heart_hight':'心率高报警','circle':'围栏报警','polygon':'围栏报价','rectangle':'围栏报价',
                             'fall_down':'摔倒报警','low_power':'低电量报警','stop_alarm':'停留报警'}
            return alarm_kind_dict[d.kind]
          }},
          {field: 'content', title: '报警参数',width:120,templet:function(d){
            if(d.kind=='circle' | d.kind=='polygon' | d.kind=='rectangle' ){
              var efe_con=eval(d.content)
              var inout=efe_con[1];
              var inout_dict={'in':'进入','out':'出'}
              return inout_dict[inout]+efe_con[0]
            }
            return d.content
            
          }},
	        {field: 'location', title: '报警地点',width:120,templet:function(d){
            // var loca=eval(d.location);
            // if(loca[0]==0 | loca[0]=='0'){
            //   return '地址为空'
            // }else{
            //   return '<button id="alarm'+d.id+'" class="layui-btn layui-btn-sm" onclick="alarm_location('+loca[0]+','+loca[1]+',\''+d.device_id+'\')">展示地址</button>'
            // }
            // return d.location
            return ''
          }},
	        {field: 's_time', title: '报警时间'},
	        {title: '操作',width:80,templet: '#alarm_table_bar', fixed: "right", align: "center"}
		    ]],
		    page: true
		  });



    }
    ,btn1: function(){
      layer.closeAll();
    }
  });
};

var alarm_location=function(lng,lat,dev){
  // console.log(loca)
  // loca=eval(loca)
  // console.log(loca)
  turn_to_page('dynamic')
  var dev_data=get_detail_from_id(device,dev)
  dev_data['lng']=lng
  dev_data['lat']=lat
  layer.closeAll()
  if(lng==0 | lng=='0'){
    layer.msg('地址为空')
    return false
  }
  setTimeout(function(){on_check(dev_data)},1000)
    
  // var geoc = new BMap.Geocoder(); 
  // var pt=new BMap.Point(loca[0],loca[1])
  // var location
  //     geoc.getLocation(pt, function(rs){
  //     var addComp = rs.address
  //     if(rs.surroundingPois.length!=0){
  //       // console.log(rs)
  //        location=addComp+','+rs.surroundingPois[0]['title']
  //      }else{
  //         location=addComp
  //      }
  //      console.log(location)
  //      $('#alarm'+dev).text(location)
  //      return location
  //    })
}
// 报警信息的数量展示,声音和弹窗

var alarm_show_func=function(){
	var alarm_num=alarm_data.length;
	var alarm_remine=user_self_detail['alarm_audio']
	var alarm_table_show=user_self_detail['alarm_show']
	// console.log(alarm_num,alarm_remine)
	$('#alarm_num_show').text(alarm_num)
	if(alarm_num>0 && alarm_remine==true){
		var audio_play=document.getElementById('alarm_audio_play');
    // audio_play.play();
    // setTimeout(function(){},1000)
	};
	if(alarm_num>0 && alarm_table_show==true){
		alarm_detail_modal()
	}
}
$(function(){
  alarm_show_func();
})

// 报警\设备信息刷新
var real_time_refresh=function(){
  $.ajax({
    type: 'GET',
    url:'?what=alarm',
    async:true,
    dataType: 'json',
    success: function(data) {
      // console.log(refresh_alarm_data)
      alarm_data=data.alarm_data
      device=data.device
      alarm_show_func()
    },
  });               
setTimeout(function(){
  real_time_refresh()
},param_refresh_time_control)
}

setTimeout(function(){
  real_time_refresh()
},param_refresh_time_control)


 //监听批量报警处理
table.on('toolbar(alarm_detail_table)', function(obj){
	if(user_self[0]['username']=='demo'){
      layer.msg('无此权限！')
      return false
    }
	var check_data = table.checkStatus(obj.config.id).data;
	var alarm_device_id = [];
	if(obj.event=='all_alarm_handle'){
		for(var i=0;i<alarm_data.length;i++){
			alarm_device_id.push(alarm_data[i]['id'])
		}
	}
	if(check_data.length==0 && alarm_device_id.length==0){
		layer.msg('请选择需要处理的设备ID')
	}else{
		for(var i=0;i<check_data.length;i++){
			alarm_device_id.push(check_data[i]['id'])
		}
		alarm_handle_ajax(alarm_device_id)
	}
});

// 监听单个报警处理
table.on('tool(alarm_detail_table)',function(obj){
	var alarm_device_id=[obj.data.id]
	alarm_handle_ajax(alarm_device_id)

})
// 报警数据处理
var alarm_handle_ajax=function(alarm_device_id,alarm_handle_mark){
	alarm_device_id=JSON.stringify(alarm_device_id)
	layer.open({
            type: 1
            ,title:'设备ID： '+JSON.stringify(alarm_device_id)
            ,area:['300px','300px']
            ,offset:'60px'  
            ,id: 'alarm_handle_mark' //防止重复弹出
            ,content:$('#alarm_handle_mark_form')
            ,btn: ['提交','关闭']
            ,shade: 0 //不显示遮罩
            ,btn1: function(layero,index){

                var alarm_handle_mark=form.val('alarm_handle_mark_form');
                if(alarm_handle_mark['alarm_handle_mark']==''){
                	alarm_handle_mark='autocomplete'
                };
                
                var data={'device_id':alarm_device_id,'alarm_handle_mark':alarm_handle_mark}
			    $.ajax({
			      type: 'POST',
			      data:data,
			      url:'?what=alarm_handle',
			      async:true,
			      dataType: 'json',
			      success: function(dd) {
              alarm_data=dd
			        alarm_detail_modal()
			        layer.msg('处理成功')
				    },
				  });
			    layer.closeAll()
            }
            ,btn2: function(layero,index){
              layer.close(index.selector);
            }
          });

}

// 报警信息处理，单个处理和批量处理


// 实时报警展示/处理结束


// 刷新之后默认加载的页面
var web_name = window.location.hash;
if(web_name==null | web_name==''){
  web_name='dynamic'
  if(user_permi=='superuser'){
    web_name='kanban'
  }
}else{
  web_name=web_name.slice(1)
}

// ---页面跳转start----//

var turn_to_page=function (page_id) {
  var wait_for_ready = layer.load(1);
  $(function(){
    console.log('ready go')
    layer.close(wait_for_ready); 
  })
  console.log(page_id)
    $('.layui-body').load("/static/web/"+page_id+".html")
    if(page_id=='dynamic' | page_id=='dynamic_gd'){
      $('.layui-side').show()
      $('.layui-body').attr('style','padding:0px;bottom:0px;top:60px;left:300px')
      $('.layui-footer').hide()
      $('.layui-header').show()
    }else if(page_id=='trail' | page_id=='efence' | page_id=='interact'){
      $('.layui-body').attr('style','padding:0px;bottom:0px;left:0px') 
      $('.layui-side').hide()
      $('.layui-footer').hide()
    }else if(page_id=='kanban' | page_id=='efence' | page_id=='interact'){
      $('.layui-body').attr('style','padding:0px;bottom:0px;top:0px;left:0px') 
      $('.layui-side').hide()
      $('.layui-footer').hide()
      $('.layui-header').hide()
    }else{
      $('.layui-body').attr('style','padding:10px;bottom:0px;left:0px') 
      $('.layui-side').hide()
      $('.layui-footer').hide()
    }
  }
turn_to_page(web_name)

// ---页面跳转end----//

// 存储跳转到轨迹回放页面的设备id
var trail_device='';
// 搜索功能
var search_func=function(tagret_data,search_key,target_field1,target_field2){
  // console.log(tagret_data,search_key,target_field1,target_field2)
  result_data=[]
  for(var i=0;i<tagret_data.length;i++){
    var search_re1=tagret_data[i][target_field1].search(search_key)
    var search_re2=tagret_data[i][target_field2].search(search_key)
    if(search_re1!==-1 | search_re2!==-1){
      result_data.push(tagret_data[i])
    }
  }
  return result_data
}

// 监听设备搜索操作
form.on('submit(dev-search-btn)', function (data) {

  var search_key = data.field['search_key'];
  if(search_key!==''){
    // 调用index页面搜索函数
    var search_result=search_func(device,search_key,'user_name','device_id')
    // 表格重载
    device_list_table(search_result)
  }else{
    device_list_table(device)
  }
  return false;
});


// 某用户设备状态（在线，离线，报警，休眠）统计函数
var dev_status_num=function(user_name,user_title){
  var query_status={'online':'on_off_line','sleep':'sleep_status','offline':'on_off_line','alarm':'alarm_status'}
  var dev_status={}
  for(var k in query_status){
    dev_status[k]=[]
    for(var i=0;i<device.length;i++){
      if(user_name=='all'){
        if(device[i][query_status[k]]==k){
          dev_status[k].push(device[i])
        }
      }else{
        if(device[i]['owner']==user_name && device[i][query_status[k]]==k){
          dev_status[k].push(device[i])
        }
      }
    }
  } ;
  // 把各种状态设备的数量显示到相应的位置
  var status_show_dict={'online':'在线','sleep':'休眠','offline':'离线','alarm':'报警'}
  
  for(var k in dev_status){
    $('#dev_'+k).text(status_show_dict[k]+'('+dev_status[k].length.toString()+')')
  }
  // 某个用户的设备总数量
  var total_num=0;
  if(user_name=='all'){
    total_num=device.length
  }else{
    for(var i=0;i<device.length;i++){
      if(device[i]['owner']==user_name){
        total_num+=1
      }
    }
  }
  $('#user_chosed').text(user_title+'('+total_num.toString()+')')

  return dev_status
}

var dev_status_detail=dev_status_num('all','全部')

// 通过设备id获取设备具体信息
var get_detail_from_id=function(device,device_id){
  for(var i=0;i<device.length;i++){
    if(device[i].device_id==device_id){
      return device[i]
    }
  }
}

// 图片上传功能
var img_upload_func=function(div_id){
  upload.render({
  elem: '#'+div_id
  ,auto: false
  ,choose: function(obj){
    obj.preview(function(index, file, result){
      // result是图片 base64编码
      $('#'+div_id).attr('src',result)
    });
  }
});
}

// 设备单选框填充
var fill_raido_func=function(fill_data,list_id,kind,key='device_id'){
  $('#'+list_id).empty()
  if(kind=='bind_dev'){
    for (var i = fill_data.length - 1; i >= 0; i--) {
      if(fill_data[i]['user_detail']==0){
        var option='<option>'+fill_data[i]['device_id']+'</option>'
        $('#'+list_id).append(option)
      }
    }
  }else{
    for (var i = fill_data.length - 1; i >= 0; i--) {
      var option='<option>'+fill_data[i][key]+'</option>'
      $('#'+list_id).append(option)
    }
  }
}

// 首次用户数据加载
var main_data;
var get_init_data=function(url,show_func=''){
  $.ajax({
      type: 'GET',
      url:"/"+url+"/?what=get_init_data",
      async:true,
      dataType: 'json',
      success: function(data) {
        console.log('success',data)
        if(show_func!==''){
          show_func(data.main)
        }
        main_data=data
      },
      error:function(e){
        console.log(e)
      }
  });
}

// 数据上传后台
var base_info_ajax=function(base_info,url,handle_kind,show_func=''){
  base_info=JSON.stringify(base_info);
  // console.log(base_info)
  $.ajax({
    type: 'POST',
    data:{base_info},
    url:"/"+url+"/?what="+handle_kind,
    async:true,
    dataType: 'json',
    success: function(res) {
      console.log(res)
      if (res.code==1000){
        var data=res.data
        console.log(data)
        if(show_func!==''){
          show_func(data)
        }
        layer.closeAll();
        layer.msg('操作成功')
        // location.reload()
      }else{
        layer.msg(res.error)
      }  
    },
  })
}

// 获取当前时间
setInterval(function(){
  laydate.render({
  elem: '#get_current_time'
  ,type: 'datetime'
  ,value:new Date()
  ,btns: ['clear','now', 'confirm']
  });
},1000)

</script>
</body>
</html>
